/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.core.event;


import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataProject;
import com.inspur.edp.lcm.metadata.api.entity.OperationEnum;
import com.inspur.edp.lcm.metadata.api.exception.ErrorCodes;
import com.inspur.edp.lcm.metadata.api.exception.LcmFileDevException;
import com.inspur.edp.lcm.metadata.api.exception.LcmMetadataDevException;
import com.inspur.edp.lcm.metadata.common.FileServiceImp;
import com.inspur.edp.lcm.metadata.core.MetadataCoreManager;
import com.inspur.edp.lcm.metadata.core.MetadataProjectCoreService;
import com.inspur.edp.lcm.metadata.spi.event.MetadataEventArgs;
import com.inspur.edp.lcm.metadata.spi.event.MetadataEventListener;

import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

public class MetadataEventListenerImpl implements MetadataEventListener {
	private static final String RES = ".res";
	private static final String LRES = ".lres";
	private static final String EN_LRES = ".en.lres";
	private static final String ZH_CHT_LRES = ".zh-CHT.lres";

	private final MetadataCoreManager metadataCoreManager = MetadataCoreManager.getCurrent();
	private final FileServiceImp fileService = new FileServiceImp();
	@Override
	public void fireMetadataSavingEvent(MetadataEventArgs args) {}

	@Override
	public void fireMetadataSavedEvent(MetadataEventArgs args) {
		// 更新文件sha1
		new MetadataProjectCoreService().updateContentChanges(args.getPath(), args.getMetadataStr(), OperationEnum.METADATA_SAVE);
	}

	@Override
	public void fireMetadataDeletingEvent(MetadataEventArgs args) {
		// 找到工程下的所有元数据
		MetadataProject project = MetadataProjectCoreService.getCurrent().getMetadataProjInfo(args.getPath());
		List<GspMetadata> metadataList = MetadataCoreManager.getCurrent().getMetadataList(project.getProjectPath());

		metadataList.forEach(metadata -> {
			if (metadata.getRefs() != null && !metadata.getHeader().getId().equals(args.getMetadata().getHeader().getId())) {
				metadata.getRefs().forEach(item -> {
					if (item.getDependentMetadata().getId().equals(args.getMetadata().getHeader().getId())) {
						throw new LcmMetadataDevException(ErrorCodes.ECP_METADATA_DEV_0007, metadata.getHeader().getFileName());
					}
				});
			}
		});
	}

	@Override
	public void fireMetadataDeletedEvent(MetadataEventArgs args) {
		if(args == null || args.getMetadata() == null || args.getMetadata().getHeader() == null || args.getPath().endsWith(LRES)){
			return;
		}
		// 元数据所在文件夹路径
		String absolutePath = Paths.get(args.getPath()).getParent().toString();
		String metadataFileName;
		List<String> fileExtensions;

		// 删除资源元数据和多语元数据
		if(args.getPath().endsWith(RES)){
			metadataFileName = args.getMetadata().getHeader().getCode();
			fileExtensions = Arrays.asList(EN_LRES, ZH_CHT_LRES);
		}else{
			metadataFileName = args.getMetadata().getHeader().getFileName();
			fileExtensions = Arrays.asList(RES, EN_LRES, ZH_CHT_LRES);
		}

		for (String extension : fileExtensions) {
			String filePath = fileService.getCombinePath(absolutePath, metadataFileName + extension);
			try {
				if (metadataCoreManager.isMetadataExist(filePath)) {
					metadataCoreManager.deleteMetadata(absolutePath, metadataFileName + extension);
				}
			} catch (Exception e) {
				throw new LcmFileDevException(e, ErrorCodes.ECP_FILE_DEV_0011, filePath);
			}
		}
	}
}
